package com.aletto.general_store.presenters;

import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.aletto.general_store.R;
import com.aletto.general_store.data.DataRepository;
import com.aletto.general_store.data.MockDataSource;
import com.aletto.general_store.data.model.Address;
import com.aletto.general_store.data.model.Response;
import com.aletto.general_store.ui.HotSearchItemDecoration;
import com.aletto.general_store.ui.activities.SearchDetailsActivity;
import com.aletto.general_store.ui.adapters.SearchHistoryAdapter;
import com.aletto.general_store.ui.adapters.SearchKeywordAdapter;
import com.aletto.general_store.ui.popup.GoodsStoreSwitchPopup;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.sisyphus.spinach.core.INetTask;
import com.sisyphus.spinach.network.presenters.NetSingleTask;
import com.sisyphus.spinach.network.views.QuickList;
import com.sisyphus.spinach.ui.configs.impl.DefaultTemplate;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Lifecycle;
import androidx.recyclerview.widget.RecyclerView;

public class SearchKeywordTemplate extends DefaultTemplate<List<String>> implements TextWatcher {

    private int searchType = GoodsStoreSwitchPopup.GOODS_TYPE;
    private String keyword;
    private final Lifecycle mLifecycle;
    private final RecyclerView mRecyclerView;

    private final SearchHistoryPresenter mPresenter;


    public SearchKeywordTemplate(RecyclerView parent, AppCompatActivity activity) {
        super(parent);
        mRecyclerView = parent;
        parent.setVisibility(View.GONE);
        mLifecycle = activity.getLifecycle();

        // 搜索
        Button searchButton = activity.findViewById(R.id.search_button);
        EditText searchContentEdit = activity.findViewById(R.id.search_content_edit);
        searchContentEdit.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH && !TextUtils.isEmpty(searchContentEdit.getText())) {
                search(v.getContext());
                return true;
            }

            return false;
        });

        searchButton.setOnClickListener(v -> {
            if (!TextUtils.isEmpty(searchContentEdit.getText())) {
                search(v.getContext());
            }
        });

        // 搜索历史
        ImageView clearAllImage = activity.findViewById(R.id.iv_clear_all);
        View searchHistoryLayout = activity.findViewById(R.id.search_history_layout);
        RecyclerView historySearchRecycler = activity.findViewById(R.id.recycler_history_search);
        searchHistoryLayout.setVisibility(View.GONE);
        historySearchRecycler.setVisibility(View.GONE);

        historySearchRecycler.addItemDecoration(new HotSearchItemDecoration());
        SearchHistoryAdapter searchHistoryAdapter = new SearchHistoryAdapter();
        searchHistoryAdapter.setOnItemClickListener((adapter, view, position) -> {
            Context context = view.getContext();
            context.startActivity(SearchDetailsActivity.newIntent(context, searchHistoryAdapter.getItem(position), searchType));
        });

        historySearchRecycler.setAdapter(searchHistoryAdapter);
        mPresenter = new SearchHistoryPresenter();
        mPresenter.bind(new QuickList<>(searchHistoryAdapter) {
            @Override
            public void success(List<String> data) {
                super.success(data);
                if (data == null || data.isEmpty()) {
                    searchHistoryLayout.setVisibility(View.GONE);
                    historySearchRecycler.setVisibility(View.GONE);

                } else {
                    searchHistoryLayout.setVisibility(View.VISIBLE);
                    historySearchRecycler.setVisibility(View.VISIBLE);
                }
            }
        });

        mPresenter.findAll();

        clearAllImage.setOnClickListener(v -> mPresenter.clear());
    }

    public void setParams(int searchType) {
        this.searchType = searchType;
    }

    @Override
    public INetTask.View<List<String>> view() {
        SearchKeywordAdapter adapter = new SearchKeywordAdapter(keyword);

        adapter.setOnItemClickListener((a, view, position) -> search(view.getContext()));

        mRecyclerView.setAdapter(adapter);
        return new QuickList<>(adapter) {
            @Override
            public void success(List<String> data) {
                super.success(data);
                mRecyclerView.setVisibility(View.VISIBLE);
            }
        };
    }

    private void search(Context context) {
        mPresenter.add(keyword); // 添加记录
        context.startActivity(SearchDetailsActivity.newIntent(context, keyword, searchType));
    }

    @Override
    public INetTask.Presenter<List<String>, INetTask.View<List<String>>> presenter() {
        return new NetSingleTask<>(DataRepository.getInstance().searchPrompt(searchType, keyword));
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (TextUtils.isEmpty(s)) {
            mRecyclerView.setVisibility(View.GONE);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {
        if (!TextUtils.isEmpty(s)) {
            keyword = s.toString();
            execute(mLifecycle);
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

}
